package com.example;

import me.tongfei.progressbar.ProgressBar;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.Normalizer;

public class VideoDownloader {

    // 清理文件名（保持原逻辑）
    private static String sanitizeFileName(String name) {
        String normalized = Normalizer.normalize(name, Normalizer.Form.NFD)
                .replaceAll("[^\\p{ASCII}]", "");
        return normalized.replaceAll("[\\\\/:*?\"<>|]", "_");
    }

    // 修正后的下载方法（解决线程状态异常）
    public static boolean downloadVideo(String videoUrl, String savePath, String fileName) {
        File dir = new File(savePath);
        if (!dir.exists() && !dir.mkdirs()) {
            System.err.println("无法创建目录: " + savePath);
            return false;
        }

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(videoUrl);

            try (CloseableHttpResponse response = httpClient.execute(request);
                 InputStream is = response.getEntity().getContent()) {

                // 获取文件大小
                long totalSize = response.getEntity().getContentLength();


                try (ProgressBar pb = new ProgressBar(fileName, totalSize)) { // 使用 try-with-resources 自动管理

                    // 获取文件扩展名
                    String ext = "mp4";
                    int dotIndex = videoUrl.lastIndexOf('.');
                    if (dotIndex != -1) {
                        ext = videoUrl.substring(dotIndex + 1);
                    }

                    // 写入文件并更新进度
                    File outputFile = new File(dir, fileName + "." + ext);
                    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, bytesRead);
                            pb.stepBy(bytesRead); // 自动更新进度
                        }
                    }
                } // 进度条在此处自动关闭
                return true;
            }
        } catch (Exception e) {
            System.err.println("下载失败: " + videoUrl);
            e.printStackTrace();
            return false;
        }
    }
}